<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Models\RedPacket;
use App\Http\Models\Item;
use Illuminate\Support\Facades\DB;

class RedPacketController extends Controller
{
    /**
     * 获取红包信息
     *
     * @param Request $req
     * @return void
     */
    public function info(Request $req) {
        $uid = \Auth::user();
        if(!$uid) return $this->throwError('ErrUnAuthorization');

        $red_packet_info = RedPacket::get($uid);
        $next_reward = RedPacket::nextReward($uid);
        return $this->result([
            'cycle' => $red_packet_info['cycle'],
            'now_times' => $red_packet_info['feed_times'],
            'reward_times' => $next_reward['times'] ?? 0,
        ]);
    }

    /**
     * 点击
     *
     * @param Request $req
     * @return void
     */
    public function click(Request $req) {
        $uid = \Auth::user();
        if(!$uid) return $this->throwError('ErrUnAuthorization');

        $uinfo = DB::table('users')->where('id', $uid)->first();


        // 判断是否可以领取
        $red_packet_info = RedPacket::get($uid);
        if($red_packet_info['feed_times'] == $red_packet_info['receive_times']) {
            return $this->throwError('ErrRedPacketReceive');
        }
        $next_reward = RedPacket::nextReward($uid, $red_packet_info);
        if( $red_packet_info['feed_times'] != $next_reward['times'] ) {
            return $this->throwError('ErrRedPacketReceive');
        }

        $log_str = 'red_packet_'.$red_packet_info['cycle'].'_'.$red_packet_info['feed_times'];

        // 判断是否需要增加从头开始
        $red_packet_info['receive_times'] = $next_reward['times'];
        if(empty(RedPacket::nextReward($uid, $red_packet_info))) {
            $red_packet_info['cycle']++;
            $red_packet_info['feed_times'] = 0;
            $red_packet_info['receive_times'] = 0;
        }
        DB::beginTransaction();
        try {
            DB::table('users')->where('id', $uid)->update([
                'rp_cycle' => $red_packet_info['cycle'],
                'rp_feed_times' => $red_packet_info['feed_times'],
                'rp_receive' => $red_packet_info['receive_times'],
            ]);
        } catch(\Exception $e) {
            DB::rollBack();
            return $this->throwError('ErrFeedDbOperate', $e->getMessage());
        }
        DB::commit();

        // 发放随机奖励
        $total = 0;
        $reward_key = [];
        foreach($next_reward['rewards'] as $key=>$info) {
            $total += $info['probability'];
            $reward_key[$key] = $total;
        }
        $random = random_int(0, $total);
        $select_key = null;
        foreach($reward_key as $key=>$val) {
            if($random <= $val) {
                $select_key = $key;
                break;
            }
        }
        // $select_key = 1;
        $get_reward = $next_reward['rewards'][$select_key];
        // 判断是否是优惠券, 先减库存
        if($get_reward['type'] == 3) {
            $coupon_info = DB::table('red_packet_coupon')->where(['id'=>$get_reward['id']])->where('inventory','>',0)->first();
            if(empty($coupon_info)) {
                unset($next_reward['rewards'][$select_key]);
                if(!empty($next_reward['rewards'])) {
                    foreach($next_reward['rewards'] as $info) {
                        if($info['type'] == 2) {
                            $get_reward = $info;
                        }
                    }
                }
            } else {
                DB::statement('update `red_packet_coupon` set `inventory`=`inventory`-1 where `inventory`>0 and `id`='.$get_reward['id']);
            }
        }
        if(empty($get_reward)) {
            $get_reward = ['type'=>4];
        }
        // var_dump(
        //     $next_reward,
        //     '总权重:' . $total,
        //     '权重数组 : ',$reward_key,
        //     '随机值 : '.$random,
        //     '抽中值: '.$select_key,
        //     '奖励: ',$get_reward);
        // exit;
        // 根据随中的奖励构建奖励数组
        $reward = $return = [];
        switch($get_reward['type']) {
            // 1: 皮肤  2: 饲料 3: 券 4: 无
            case 1:
                $coupon_info = DB::table('red_packet_dressup')->where('id',$get_reward['id'])->first();
                $reward[] = ['type'=>555, 'num'=>1,'id' => $get_reward['id'], 'duration'=>($coupon_info['validity']*86400)];
                $return = [
                    'type' => 1,
                    'info' => [
                        'id' => $coupon_info['id'],
                        'name' => $coupon_info['name'],
                        'img' => $coupon_info['img_url'],
                        'durationTime' => 0
                    ],
                ];
                break;
            case 2:
                $reward[] = ['type'=>config('game.cfg.ItemTypeFodder'), 'num' => $get_reward['nums'], 'id' => config('game.cfg.ItemTypeFodder')];
                $return = [
                    'type' => 2,
                    'info' => [
                        'add_fodders' => $get_reward['nums'],
                    ],
                ];
                break;
            case 3:
                $coupon_info = DB::table('red_packet_coupon')->where(['id'=>$get_reward['id']])->first();
                if($coupon_info) {
                    $reward[] = ['type'=>config('game.cfg.ItemTypeCoupon'), 'extra' => $coupon_info['batch_number']];
                }
                $return = [
                    'type' => 3,
                    'info' => [
                        'name' => $coupon_info['coupon_name'],
                        'total_amount' => $coupon_info['total_amount'],
                        'discount_amount' => $coupon_info['discount_amount'],
                        'jump_url' => $coupon_info['jump_url'],
                    ],
                ];
                break;
            case 4:
                $return = ['type' => 4];
                break;
        }
        Item::give($uid, $reward, $uinfo, $log_str);

        if($get_reward['type'] == 1) {
            $dress_info = DB::table('dressups')->where(['userId'=>$uid, 'confId'=>$get_reward['id']])->first();
            $return['info']['durationTime'] = $dress_info['lastGetTime'] + $dress_info['durationTime'];
        }

        return $this->result($return);
    }
}
